<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync='page'
      ref="crud"
      v-model="form"
      :before-close="beforeClose"
      :permission="permissionList"
      @row-click="handleRowClick"
      @current-row-change="handleCurrentRowChange"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <!-- <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-download" plain @click="handleDown">下载模板</el-button>
        <el-upload ref='uploader' style='display:inline-block' :on-success="handleSuccess" :before-upload="beforeUpload" :show-file-list="false" :headers='headers' action='/api/blade-basic/supplier/fileUpload' :http-request="fileChange" :disabled="isSuccsess" :on-error='handleErro'>
          <el-button type="primary" size="small" icon="el-icon-upload" :loading='isSuccsess' v-if="permission.supplier_upload">导 入</el-button>
        </el-upload>
        <el-checkbox v-model="seeMaterial" @change='changeSeeMaterial'>看材料</el-checkbox>
      </template> -->
      <template slot="menuLeft">
        <table-right
          :crud='$refs.crud'
          :data='data'
          :refreshChange='refreshChange'>
          <div class="top-bar__item iconDiv" @click="handleDelete" v-if="permission.public_productbom_delete">
            <i class="el-icon-delete" style="font-size:20px;"></i>
            <span style="font-size: 12px;color:#1e1e1e;">&nbsp;批量删除</span>
          </div>
        </table-right>
      </template>
      <template slot-scope="{scope,row}" slot="menuForm">
        <el-button icon="el-icon-circle-plus" v-if="type=='add'" v-loading="goon" size="mini" plain type="primary"
                   @click.stop="saveAndGoon()">保存并继续
        </el-button>
      </template>
      <template slot-scope="scope" slot="addForm">
        <el-button type="primary" icon="el-icon-plus" @click="addMaterial"></el-button>
      </template>
      <template slot="infoForm" slot-scope="scope">
        <avue-crud ref="infoCrud" class="noMenuHtml" :option="infoOption" :data="childPrdBomList" @row-save="addSave"
                   @row-update="addUpdate" @row-del="inforRowDel">
        </avue-crud>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.crud.rowView(row,row.$index)"
                     v-if="permission.public_productbom_view"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="复制" placement="bottom">
          <el-button icon="el-icon-copy-document" size="small" type="text" @click.stop="copyBom(row,row.$index)"
                     v-if="permission.public_productbom_copy"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" type="text" @click.stop="$refs.crud.rowEdit(row,row.$index)"
                     :disabled="row.auditStatus=='2'||row.auditStatus=='3'"
                     v-if="permission.public_productbom_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)"
                     :disabled="row.auditStatus=='2'||row.auditStatus=='3'"
                     v-if="permission.public_productbom_delete"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="历史版本" placement="bottom">
          <el-button icon="el-icon-folder-opened" size="small" type="text"
                     @click.stop="showBomHistoryFn(row)"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <el-tabs type="border-card" class='tabs'>
      <el-tab-pane label="产品BOM">
        <Bom :BOMdata="BOMdata" noMenuHtml="true" @getBom="getBom" :addBtn="false"
             :viewBtn="permission.public_productbom_view" :editBtn="permission.public_productbom_edit"
             :delBtn="permission.public_productbom_delete" type='edit' bomType="product"></Bom>
      </el-tab-pane>
    </el-tabs>
    <el-drawer :wrapperClosable='false' title="BOM历史" :visible.sync="bomHistory" size="75%" :append-to-body="true">
      <bomHistoryCom :form="bomMainData" v-if="bomHistory" @close="bomHistory=false"/>
    </el-drawer>

    <el-drawer :wrapperClosable='false' :title="title" :visible.sync="showDialog" size="75%" append-to-body>
      <product-bom-main @reload="reload" @closeAfter="closeAfter" :openType="openType" :row="clickRow" :type="openType"
                        @close="showDialog=false" v-if="showDialog"/>
    </el-drawer>
  </basic-container>
</template>

<script>
import Bom from './bom/index';
import * as product from '@/views/publicbom/bom/ajax.js';
import {getUnitList} from '@/api/basic/unit';
import {getMaterialgroupList} from '@/api/project/productData/baseData';
// import { getPrdProcess } from '@/api/project/productData/processData';
import {mapGetters, mapState} from 'vuex';
import {init, offFunction} from '@/mixins/init';
import {qmRemove} from '@/api/zidian';
import {infoOption} from '@/const/project/bom';
import bomHistoryCom from './bomHistory'
import ProductBomMain from "@/views/publicbom/productBomMain";

export default {
  mixins: [init,offFunction],
  components: {ProductBomMain, Bom, bomHistoryCom},
  data() {
    return {
      showDialog: false,
      bomHistory: false,
      bomMainData: {},
      isSuccsess: false,
      seeMaterial: false,
      copy: false,
      currentMaterialNo: '', //当前选中的产品编码
      query: {},
      productList: [],
      rules: [
        {
          required: true,
          message: '请选择直接上级产品',
          trigger: 'blur',
        },
      ],
      option: {
        highlightCurrentRow: true,
        searchMenuSpan: 24,
        dialogWidth: '85%',
        searchGutter: 0,
        menuWidth: 160,
        tip: false,
        emptyBtnText: '重 置',
        emptyBtnIcon: 'el-icon-refresh',
        menu: false,
        searchShow: false,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        editTitle: '编辑',
        column: [
          {
            label: '产品编码',
            minWidth: 150,
            sortable: true,
            prop: 'materialNo',
            display: false,
            search: true,
            maxlength: 15,
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入产品编码',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品名称',
            prop: 'materialName',
            search: true,
            display: false,
            editDisabled: false,
            minWidth: 150,
            sortable: true,
            overHidden: true,
            maxlength: 32,
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入产品名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品图号',
            prop: 'productDrawingNo',
            minWidth: 150,
            sortable: true,
            display: false,
          },
          {
            label: '内部图号',
            prop: 'innerDrawingNo',
            minWidth: 150,
            disabled: true,
            display: false,
            sortable: true,
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入产品图号',
                trigger: 'blur',
              },
            ],
          },
          // {
          //   label: '产品标识',
          //   prop: 'materialFlag',
          //   maxlength: 10,
          //   display: false,
          // },
          {
            label: '产品类型',
            prop: 'productType',
            display: false,
            search: true,
            searchValue: 'PC',
            type: 'select',
            dicUrl: '/api/materialgroup/getTree?code=materials&dictKey=P',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
          {
            label: '规格',
            prop: 'specifications',
            maxlength: 30,
            minWidth: 120,
            overHidden: true,
            display: false,
          },
          {
            label: '型号',
            prop: 'model',
            maxlength: 30,
            minWidth: 120,
            overHidden: true,
            display: false,
          },
          // {
          //   label: '审核状态',
          //   prop: 'auditStatus',
          //   sortable: true,
          //   display: false,
          //   minWidth: 100,
          //   type: 'select',
          //   dicUrl: '/api/blade-system/dict/dictionary?code=approval_status',
          //   props: {
          //     label: 'dictValue',
          //     value: 'dictKey',
          //   },
          //   search: true,
          //   maxlength: 32,
          //   span: 12,
          // },
          // {
          //   label: '审核时间',
          //   prop: 'auditDatetime',
          //   minWidth: 140,
          //   type: 'datetime',
          //   sortable: true,
          //   display: false,
          //   format: 'yyyy-MM-dd HH:mm:ss',
          //   valueFormat: 'yyyy-MM-dd HH:mm:ss',
          // },
          // {
          //   label: 'BOM审批人',
          //   prop: 'approver',
          //   span: 24,
          //   maxlength: 30,
          //   minWidth: 100,
          //   display: false,
          //   overHidden: true,
          // },
          // {
          //   label: 'BOM版本号',
          //   prop: 'version',
          //   span: 24,
          //   minWidth: 100,
          //   maxlength: 30,
          //   display: false,
          // },
        ],
        group: [
          {
            label: 'BOM信息',
            prop: 'infor',
            icon: 'el-icon-edit-outline',
            column: [
              {
                label: '产品',
                prop: 'materialNo',
                filterable: true,
                type: 'select',
                dicData: [],
                span: 12,
                rules: [
                  {
                    required: true,
                    message: '请选择产品',
                    trigger: 'blur',
                  },
                ],
              },
            ],
          },
          {
            label: 'BOM组成',
            prop: 'jbxx',
            icon: 'el-icon-edit-outline',
            column: [
              {
                label: '零件类型',
                prop: 'bomMaterialType',
                type: 'cascader',
                viewDisplay: false,
                span: 7,
                // cascaderItem: ['materialGroupNo'],
                dicUrl: '/api/materialinfo/getTree?code=materials&dictKey=P,M',
                // dicUrl: '/api/materialgroup/getTree?code=materials',
                props: {
                  label: 'dictValue',
                  value: 'dictKey',
                },
              },
              {
                label: '零件组',
                prop: 'materialGroupNo',
                type: 'select',
                filterable: true,
                viewDisplay: false,
                span: 7,
                props: {
                  label: 'materialGroupName',
                  value: 'materialGroupNo',
                },
                // cascaderIndex: 0,
                dicData: [],
                // dicUrl: `/api/materialgroup/list?materialType={{key}}`,
              },
              {
                label: '零件',
                prop: 'bomNo',
                type: 'select',
                filterable: true,
                viewDisplay: false,
                span: 7,
                dicData: [],
              },
              {
                label: '',
                labelWidth: 0,
                viewDisplay: false,
                span: 3,
                prop: 'add',
                hide: true,
                formslot: true,
              },
              {
                labelWidth: 0,
                label: '',
                prop: 'info',
                span: 24,
                hide: true,
                formslot: true,
              },
            ],
          },
        ],
      },
      form: {
        // materialType: [],
        // materialGroupNo: '',
      },
      infoOption: infoOption,
      childPrdBomList: [],
      materialList: [],
      BOMdata: [],
    };
  },
  computed: {
    ...mapGetters(['permission']), //权限映射
    ...mapState({
      headers: (state) => ({'Blade-Auth': `bearer ${state.user.token}`}),
    }),
    permissionList() {
      //按钮权限设置
      return {
        addBtn: this.vaildData(this.permission.public_productbom_add, false),
        viewBtn: this.vaildData(this.permission.public_productbom_view, false),
        delBtn: this.vaildData(this.permission.public_productbom_delete, false),
        editBtn: this.vaildData(this.permission.public_productbom_edit, false),
      };
    },
    getId() {
      return this.form.id;
    },
    productDrawingNos() {
      //所有勾选的id
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.productDrawingNo);
      });
      return ids.join(',');
    },
  },
  mounted() {
    setTimeout(() => {
      this.$EventBus.$emit('publicBtn', {add: this.permission.public_productbom_add})
    }, 200)
    this.$EventBus.$on("publicBtnClick", (params) => {
      if (params == "add") {
        this.addFn()
      } else if (params == "edit") {
        this.rowEdit(this.clickRow)
      } else if (params == "del") {
        this.rowDel(this.clickRow)
      } else if (params == 'view') {
        this.rowView(this.clickRow)
      } else if (params == 'copy') {
        this.copyBom(this.clickRow, this.clickRow.$index);
      } else if (params == 'historyVersion') {
        this.showBomHistoryFn(this.clickRow)
      }
    });
  },
  watch: {
    'form.bomMaterialType'(newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        getMaterialgroupList({materialType: newVal.join(',')}).then((res) => {
          let data = res.data.data;
          const column = this.findObject(this.option.group[1].column, 'materialGroupNo');
          if (res.data.data.length == 0) {
            column.dicData.length = 0;
            column.dicData = [];
          } else {
            column.dicData = data;
          }
        });
        product.materialList({materialType: newVal[1]}).then((res) => {
          const column = this.findObject(this.option.group, 'bomNo');
          if (res.data.data.length == 0) {
            column.dicData.length = 0;
            // column.dicData = [];
          } else {
            this.materialList = res.data.data;
            column.dicData = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (newVal && newVal.length == 0) {
        this.$set(this.form, 'materialGroupNo', null);
        this.$set(this.form, 'bomNo', null);
      }
      if (oldVal && oldVal.length > 0 && newVal && newVal.length > 0 && newVal.join(',') !== oldVal.join(',')) {
        this.$set(this.form, 'materialGroupNo', null);
        this.$set(this.form, 'bomNo', null);
      }
    },
    'form.materialGroupNo'(newVal, oldVal) {
      if (newVal) {
        this.$set(this.form, 'bomNo', null);
      }
      if (newVal && this.form.bomMaterialType.length > 0) {
        product.materialList({materialType: this.form.bomMaterialType[1], materialGroupNo: newVal}).then((res) => {
          const column = this.findObject(this.option.group, 'bomNo');
          if (res.data.data.length == 0) {
            column.dicData.length = 0;
            // column.dicData = [];
          } else {
            this.materialList = res.data.data;
            column.dicData = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                // label: item.materialName + '(' + item.specifications + '/' + item.model + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (!newVal || (newVal && this.form.bomMaterialType.length == 0)) {
        this.$set(this.form, 'bomNo', null);
      }
    },
  },
  created() {
    this.query.productType = 'PC';
  },
  methods: {
    handleRowClick(row) {
      this.clickRow = row;
      this.$EventBus.$emit('publicBtn', {
        add: this.permission.public_productbom_add,
        del: this.permission.public_productbom_delete && row.auditStatus != 2 && row.auditStatus != 3,
        view: this.permission.public_productbom_view,
        edit: this.permission.public_productbom_edit && row.auditStatus != 2 && row.auditStatus != 3,
        copy: this.permission.public_productbom_copy,
        // historyVersion: true,
      });
    },
    reload() {
      this.showDialog = false;
      this.onLoad(this.page);
    },
    closeAfter() {
      this.onLoad(this.page);
    },
    addFn() {
      this.title = '新增产品BOM';
      this.openType = 'add';
      this.showDialog = true;
    },
    rowEdit() {
      this.title = '编辑产品BOM';
      this.openType = 'edit';
      this.showDialog = true;
    },
    rowView() {
      this.title = '查看产品BOM';
      this.openType = 'view';
      this.showDialog = true;
    },
    copyBom() {
      this.title = '复制产品BOM';
      this.openType = 'copy';
      this.showDialog = true;
    },
    addMaterial() {
      if (!this.form.bomNo) {
        this.$message.error('请选择要添加的零件');
        return;
      }
      if (this.form.bomNo) {
        if (!this.form.materialNo) {
          this.$message.error('请先选择产品');
          return;
        }
        if (this.childPrdBomList.length > 0) {
          let isHave = false;
          isHave = this.childPrdBomList.some((item) => item.materialNo == this.form.bomNo);
          if (isHave) {
            this.$message.error('零件已添加，不可重复添加');
            return;
          }
        }
        this.materialList.every((item) => {
          if (this.form.bomNo == item.materialNo) {
            if (this.form.materialNo && this.form.materialNo == this.form.bomNo) {
              this.$message.error('添加的零件不可以与产品相同');
            } else {
              item.$cellEdit = true;
              item.quota = '';
              item.lossRate = '';
              delete item.id
              this.childPrdBomList.push(item);
            }
            return false;
          } else {
            return true;
          }
        });
      }
    },
    validQuotaNoMessage(quota) {
      let reg = /^[0-9]*\/+[1-9][0-9]*$/; //分数验证
      let reg1 = /^([0-9]|[1-9][0-9])(\.\d{1,4})?$/; //100以内的整数或最多四位小数验证
      if (quota) {
        if (quota == '0') {
          return false;
        } else if (reg.test(quota)) {
          let arr = quota.split('/');
          if (arr[0] == 0 || arr[1] == 0 || arr[0] >= arr[1]) {
            return false;
          } else {
            return true;
          }
        } else if (!reg.test(quota) && !reg1.test(quota)) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    validQuota(quota) {
      let reg = /^[0-9]*\/+[1-9][0-9]*$/; //分数验证
      let reg1 = /^([0-9]|[1-9][0-9])(\.\d{1,4})?$/; //100以内的整数或最多四位小数验证
      if (quota) {
        if (quota == '0') {
          this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
          return false;
        } else if (reg.test(quota)) {
          let arr = quota.split('/');
          if (arr[0] == 0 || arr[1] == 0 || arr[0] >= arr[1]) {
            this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
            return false;
          } else {
            return true;
          }
        } else if (!reg.test(quota) && !reg1.test(quota)) {
          this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
          return false;
        } else {
          return true;
        }
      } else {
        this.$message.error('请输入定额');
        return false;
      }
    },
    validLossRate(lossRate) {
      if (lossRate) {
        let valid = /^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/.test(lossRate);
        if (valid) {
          return true;
        } else {
          this.$message.error('损耗率请输入100以内的正整数或最多两位小数');
          return false;
        }
      } else {
        this.$message.error('请输入损耗率');
        return false;
      }
    },
    addUpdate(form, index, done, loading) {
      let validQuota = this.validQuota(form.quota);
      if (validQuota) {
        let validLossRate = this.validLossRate(form.lossRate);
        if (validLossRate) {
          done();
        } else {
          loading();
        }
      } else {
        loading();
      }
    },
    inforRowDel(row, index) {
      this.childPrdBomList.splice(index, 1);
    },
    fileChange(param, type) {
      let formData = new FormData();
      formData.append('file', param.file);
      formData.append('type', '1'); //主数据
      product
        .fileUpload(formData)
        .then(() => {
          this.isSuccsess = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        })
        .catch((error) => {
          console.log(error);
          this.isSuccsess = false;
          this.$refs.uploader.clearFiles();
        });
    },
    getBom() {
      product.productBomList(this.currentMaterialNo).then((res) => {
        const data = res.data.data;
        this.BOMdata = data.map(item => {
          item.materialTypes = [item.productFlag, item.productType]
          return item
        })
      });
    },
    handleCurrentRowChange(val) {
      // debugger;
      if (val) {
        this.currentMaterialNo = val.materialNo;
        this.getBom();
      } else {
        this.BOMdata = [];
      }
    },
    handleDown() {
      // product.productInforDown();
    },
    validFunction(data) {
      let equipMsg = '';
      if (data.length == 0) {
        equipMsg = `【BOM组成】不能为空`;
        this.$message.error(equipMsg);
      } else {
        data.every((item, index) => {
          if (!item.quota) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入定额`;
            this.$message.error(equipMsg);
            return false;
          } else {
            let validQuota = this.validQuotaNoMessage(item.quota);
            if (!validQuota) {
              equipMsg = `【BOM组成】第${index + 1}行 定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)`;
              this.$message.error(equipMsg);
              return false;
            }
          }
          if (!item.lossRate) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入损耗率`;
            this.$message.error(equipMsg);
            return false;
          } else if (!/^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/.test(item.lossRate)) {
            equipMsg = `【BOM组成】第${index + 1}行 损耗率请输入100以内的正整数或最多两位小数`;
            this.$message.error(equipMsg);
            return false;
          }
          return true;
        });
      }
      if (equipMsg) {
        return false;
      }
      return true;
    },
    rowSave(row, done, loading) {
      let valid = this.validFunction(this.childPrdBomList);
      if (!valid) {
        this.goon = false;
        loading();
        return;
      }
      let children = this.childPrdBomList.map((item) => {
        if (item.id) {
          delete item.id;
        }
        return item;
      });
      row.dataSource = '1';
      let content = {...row, childPrdBomList: children};
      product.bomAdd(content).then(
        () => {
          if (this.goon) {
            loading();
            for (let key in this.$refs.crud.value) {
              this.$refs.crud.value[key] = null;
            }
            this.childPrdBomList = [];
            this.childPrdBomList.length = 0;
            this.goon = false;
            this.onLoad(this.page);
          } else {
            this.onLoad(this.page);
            done();
          }
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          loading();
          // console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      //行内的编辑事件触发
      // let children = this.childPrdBomList.map((item) => {
      //   if (item.id) {
      //     delete item.id;
      //   }
      //   return item;
      // });、
      let valid = this.validFunction(this.childPrdBomList);
      if (!valid) {
        loading();
        return;
      }
      // 复制新增
      if (this.copy) {
        let children = this.childPrdBomList.map((item) => {
          if (item.id) {
            delete item.id;
          }
          return item;
        });
        row.dataSource = '1';
        row.id = null;
        let content = {...row, childPrdBomList: children};
        product.bomAdd(content).then(
          () => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          },
          (error) => {
            loading();
            // console.log(error);
          }
        );
      } else {
        // 编辑保存
        let content = {...row, childPrdBomList: this.childPrdBomList};
        product.bomUpdate(content).then(
          () => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          },
          (error) => {
            loading();
            // console.log(error);
          }
        );
      }
    },
    rowDel(row) {
      //行内的删除事件触发
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      })
        .then(() => {
          return product.bomRemove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    showBomHistoryFn(row) {
      this.bomMainData = row
      this.bomHistory = true
    },
    handleDelete() {
      //多选删除
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isApprove = false;
      isApprove = this.selectionList.some((item) => {
        return item.auditStatus != 1;
      });
      if (isApprove) {
        this.$message({
          type: 'error',
          message: '不可以删除审批中、已通过或被驳回的数据！',
        });
        return;
      }
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      })
        .then(() => {
          return product.bomRemove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.type = type;
      this.childPrdBomList.length = 0;
      this.childPrdBomList = [];
      const column0 = this.findObject(this.option.group, 'materialGroupNo');
      column0.dicData.length = 0;
      column0.dicData = [];
      const column = this.findObject(this.option.group, 'bomNo');
      column.dicData.length = 0;
      column.dicData = [];

      if (['edit', 'view'].includes(type)) {
        product.bomDetail(this.form.id).then((res) => {
          let data = res.data.data;
          this.childPrdBomList = data.childPrdBomList;
          let materialNoData = this.findObject(this.option.group, 'materialNo').dicData;
          if (materialNoData.findIndex((res) => res.value == this.form.materialNo) == -1) {
            materialNoData.unshift({
              label: this.form.materialName + '(' + this.form.materialNo + ')',
              value: this.form.materialNo,
            });
          }
          this.form = data;
          if (this.copy) {
            this.$set(this.form, 'materialNo', '');
          }
        });
      }
      if (type == 'view') {
        this.infoOption.menu = false;
      } else {
        this.infoOption.menu = true;
      }
      if (type == 'edit') {
        if (this.copy) {
          this.option.editTitle = '复制';
        } else {
          this.option.editTitle = '编辑';
        }
      }
      if (type == 'add') {
        this.$set(this.form, 'materialNo', '')
        this.$set(this.form, 'bomMaterialType', '')
        this.$set(this.form, 'materialGroupNo', '')
        this.$set(this.form, 'bomNo', '')
      }
      done();
    },
    beforeClose(done) {
      this.copy = false;
      done();
    },
    onLoad(page, params = this.query) {
      this.closeTooltip();
      //加载table
      this.query.dataSource = '1';
      this.loading = true;
      Promise.all([
        product.bomList(page.currentPage, page.pageSize, Object.assign(params, this.query)),
        product.bomproductList({flag: 'bom'}),
      ]).then((res) => {
        let data1 = res[1].data.data;
        const column = this.findObject(this.option.group, 'materialNo');
        this.productList = data1;
        column.dicData = data1.map((item) => {
          return {
            label: item.materialName + '(' + item.materialNo + ')',
            value: item.materialNo,
          };
        });
        const data = res[0].data.data;
        // this.$refs.crud.setCurrentRow();
        this.page.total = data.total;
        this.data = data.records;

        this.loading = false;
        this.selectionClear();
        if (this.data.length > 0) {
          this.$nextTick(() => {
            this.$nextTick(() => {
              this.$refs.crud.setCurrentRow(this.data[0]);
              this.handleRowClick(this.data[0])
            });
          });
        } else {
          this.BOMdata.length = 0;
          this.BOMdata = [];
        }
      });
      getUnitList().then((res) => {
        let data = res.data.data;
        const column = this.findObject(this.infoOption.column, 'unit');
        column.dicData = data.map((item) => {
          return {
            label: item.name + '(' + item.code + ')',
            value: item.code,
          };
        });
      });
    },
  },
};
</script>

<style>
.avue-crud__pagination {
  margin-top: 0;
  padding: 0;
}

.el-input-group__append {
  padding: 0 8px;
}
</style>
